package com.kpbvip.aikf.util;

import com.alibaba.fastjson.JSONObject;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import okhttp3.MediaType;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class SseUtil {
    private static final MediaType JSON = okhttp3.MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) {
        String vals="{\n" +
                "    \"chatId\": \"my_chatId\",\n" +
                "    \"stream\": true,\n" +
                "    \"detail\": false,\n" +
                "    \"responseChatItemId\": \"my_responseChatItemId\",\n" +
                "    \"variables\": {\n" +
                "        \"uid\": \"asdfadsfasfd2323\",\n" +
                "        \"name\": \"张三\"\n" +
                "    },\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \"导演是谁\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        Map<String,String> headMap= new HashMap<>();
        headMap.put("Authorization","Bearer fastgpt-zL26g2LP2tw5rxY4LGqrWjQ7LYDKh9aZWrAYKaFEbCSRZqvylTRQSvFRkqjConCkY");
        SseUtil.send("http://192.168.170.100:3000/api/v1/chat/completions",vals,headMap);
    }


    public static SseEmitter send(String url,String data2,Map<String,String> headMap) {
        SseEmitter sseEmitter = new SseEmitter();
        RequestBody body = RequestBody.create(data2, JSON);
       // FormBody formBody = new FormBody.Builder().add("prompt", prompt).build();
        Request request = new Request.Builder().url(url).post(body).headers( okhttp3.Headers.of(headMap)).build();
        // 使用EventSourceListener处理来自服务器的SSE事件
        EventSourceListener listener = new EventSourceListener() {
            @Override
            public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
                System.out.println("建立连接");

            }
            @Override
            public void onClosed(@NotNull EventSource eventSource) {
                ;   System.out.println("完成");
                sseEmitter.complete();
            }
            @Override
            public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
                try {     System.out.println("传输中：");
                    System.out.println(data);
                    sseEmitter.send(data);
                } catch (Exception e) {
                }
            }
            @Override
            public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
                sseEmitter.completeWithError(t);
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(50, TimeUnit.SECONDS).readTimeout(10, TimeUnit.MINUTES).build();
        EventSource.Factory factory = EventSources.createFactory(client);
        factory.newEventSource(request, listener);
        return sseEmitter;
    }

}
